package cn.talk.doodledemo.utils.photocodeclib;

import cn.talk.doodledemo.utils.log.LogUtils;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

/**
 * @version 1.0.1
 * @description: 渐进式解码
 * @program: Gallery
 * @Author xiaozhijun
 * @Date 2020/12/31 11:22
 */
public class IncrementalPhotoDecode implements IPhotoDecode {

    private static final String TAG = "IncrementalPhotoDecode";

    PhotoDecode photoDecode;

    private ImageSource imageSource;

    IncrementalPhotoDecode(PhotoDecode decode) {
        this.photoDecode = decode;
    }

    /**
     * 渐进式解码---第一次解码
     *
     * @param data    读取的图像数据
     * @param offset  起始位置
     * @param length  读取长度
     * @param isFinal 是否更新完成
     * @return pixelMap 解码后的图像数据
     */
    public PixelMap IncrementalDecodePhoto(byte[] data, int offset, int length, boolean isFinal) {
        LogUtils.i(TAG, "IncrementalDecodePhoto");
        PixelMap pixelMap = null;
        try {
            ImageSource.IncrementalSourceOptions incOpts = new ImageSource.IncrementalSourceOptions();
            incOpts.opts = photoDecode.sourceOptions;
            incOpts.mode = ImageSource.UpdateMode.INCREMENTAL_DATA;
            imageSource = ImageSource.createIncrementalSource(incOpts);

            imageSource.updateData(data, offset, length, isFinal);
            pixelMap = imageSource.createPixelmap(photoDecode.decodingOptions);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (isFinal) {
                imageSource.release();
            }
        }
        return pixelMap;
    }

    /**
     * 渐进式解码---更新渐进解码数据
     *
     * @param data    读取的图像数据
     * @param offset  起始位置
     * @param length  读取长度
     * @param isFinal 是否更新完成
     * @return pixelMap 解码后的图像数据
     */
    public PixelMap updateIncrementalData(byte[] data, int offset, int length, boolean isFinal) {
        PixelMap pixelMap = null;
        if (imageSource != null) {
            try {
                imageSource.updateData(data, offset, length, isFinal);
                pixelMap = imageSource.createPixelmap(photoDecode.decodingOptions);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (isFinal) {
                    imageSource.release();
                }
            }
        }
        return pixelMap;
    }

    @Override
    public PixelMap commonDecodePhoto(String filepath) {
        return photoDecode.commonDecodePhoto(filepath);
    }
}
